const fs = require("fs");
const path = require("path");
const os = require("os");
const config = require("./currentConf.json");
const platform = os.platform();
//时间戳格式化
Date.prototype.Format = function (format) {
    //eg:format="yyyy-MM-dd hh:mm:ss";

    if (!format) {
        format = "yyyy-MM-dd hh:mm:ss";
    }

    const o = {
        "M+": this.getMonth() + 1,  // month
        "d+": this.getDate(),       // day
        "H+": this.getHours(),      // hour
        "h+": this.getHours(),      // hour
        "m+": this.getMinutes(),    // minute
        "s+": this.getSeconds(),    // second
        "q+": Math.floor((this.getMonth() + 3) / 3), // quarter
        "S": this.getMilliseconds()
    };

    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "")
            .substr(4 - RegExp.$1.length));
    }

    for (let k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1
                ? o[k]
                : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }

    return format;
};

//获取服务器ip
function getServerIPAdr() {
    const interfaces = os.networkInterfaces();
    for (let devName in interfaces) {
        var iface = interfaces[devName];
        for (var i = 0; i < iface.length; i++) {
            var alias = iface[i];
            if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                return alias.address;
            }
        }
    }
}

//写入日志到文件
function writeData(data, type) {
    let log_path = config.logBookPath;
    let log_name = config.logBook.name;
    let real_path = path.join(log_path, log_name);
    data = typeof data === 'object' ? JSON.stringify(data) : data;
    let strData = getServerIPAdr() + ' - ' + new Date().toLocaleString() + ' - ' + config.logBook[type] + ': ' + data + "\n";
    //以可读写方式打开文件，并将内容写到文件末尾
    fs.appendFile(real_path, strData, {}, function (err) {
        if (err) throw err;
        // console.log("the data to append");
    });
}

module.exports = {
    error(data) {
        writeData(data, 'error');
    },

    info(data) {
        writeData(data, 'info');
    },

    debug(data) {
        if (config.logBook.debug) {
            writeData(data, 'debug');
        }
    }
};